package com.sanyang.lawyer.utils;

import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.persistence.entity.GroupEntity;
import org.activiti.engine.impl.persistence.entity.UserEntity;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ActivitiUtils {
    
    @Autowired
    private IdentityService identityService;
    
    @Autowired
    private RuntimeService runtimeService;
   
    @Autowired
    private TaskService taskService;
    
    
    //根据用户名称和用户的角色名称创建用户
    public void createUserAndGroup(String userName,String roleName){
        //创建用户
        identityService.saveUser(new UserEntity(userName));
        //设置角色和用户组的对应关系
        identityService.createMembership(userName, roleName);
    }
    
    //添加角色
    public void createRole(String roleName){
        //创建角色 
        identityService.saveGroup(new GroupEntity(roleName));
    }

    //根据角色和流程文件id开始一个流程 返回流程实例id
    public String start(String roleName,String processKey){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("group",roleName);
        String processid = runtimeService.startProcessInstanceByKey(processKey, map).getId();
        return processid;
    }
    
    //根据流程id开始下一步
    public void Mycomplete(String processid){
        //根据流程实例id返回任务对象
        Task task = taskService.createTaskQuery()
                .processInstanceId(processid).singleResult();
        String taskid = task.getId();
        System.out.println("当前流程名称"+task.getName());
        //完成流程
        taskService.complete(taskid);
    }
    
    //根据流程id判断流程是否结束
    public String ifclose(String processid){
        //判断是否结束
        ProcessInstance pro = runtimeService.
                createProcessInstanceQuery().
                processInstanceId(processid).
                singleResult();
        return pro==null?"完成":"未完成";
    }

    //根据用户查询可以执行的任务。
    public List<Task> findTaskByUserName(String assignee){
        List<Task> list=taskService.createTaskQuery().taskCandidateUser(assignee).list();
        if(list!=null && list.size()>0){
            for(Task task:list){
                System.out.println(task);
                System.out.println("任务ID："+task.getId());
                System.out.println("任务的办理人："+task.getAssignee());
                System.out.println("任务名称："+task.getName());
                System.out.println("任务的创建时间："+task.getCreateTime());
                System.out.println("流程实例ID："+task.getProcessInstanceId());
                System.out.println("#######################################");
            }
        }
        return list;
    }
    
    
}
